import React, { Component } from 'react';
import { Map, MouseTool, Polygon, Circle, Marker, Markers, InfoWindow } from 'react-amap';
import { Card, Tooltip, Col, Row, Statistic, Button } from 'antd';
import { connect } from 'umi';
import echarts from 'echarts/lib/echarts';
import { isNull } from 'lodash';
import styles from './index.less';
import { mapQueyType, beforeAdcode, groupBy, selectModel, formatterRegionCode } from '@/utils/utils';
import { RollbackOutlined } from '@ant-design/icons';

const opts = {
  //districtSearch配置项
  subdistrict: 1, //返回下一级行政区
  showbiz: false, //最后一级返回街道信息
  extensions: 'all', //是否返回行政区边界坐标点
};
// 部分区域坐标经纬度
const regionGeo = {
  530114: [102.901382, 24.839275],
  530115: [102.684987, 24.606944],
  530126: [103.311962, 24.704545],
  530127: [103.138777, 25.265087],
  530181: [102.485544, 24.841785],
  530103: [102.849044, 25.140239],
  530111: [102.983437, 25.021211],
  530112: [102.705904, 24.91436],
  530922: [100.325637, 24.239026],
  530925: [99.824419, 23.347476],
}

@connect(({ user }) => ({
  currentUser: user.currentUser,
}))
export default class HotMap extends Component {
  constructor() {
    super();
    this.state = {
      name: '昆明',
      adcode: '530000',
      level: 'province',
      queryAble: false,
      regionColors: {},
    };
    let _this = this;
    this.map = null;
    this.marker = null;
    this.walls = [];
    this.object3Dlayer = new AMap.Object3DLayer({ zIndex: 1 });
    this.polygons = [];
    this.districtSearch = null;
    this.amapEvents = {
      created: (map) => {
        //DistrictSearch插件引入
        AMap.plugin('AMap.DistrictSearch', () => {
          this.districtSearch = new AMap.DistrictSearch(opts);
        });
        map.add(this.object3Dlayer)
        this.map = map; //全局map实例  不是AMap
        if (this.districtSearch) {
          this.districtSearchByName(formatterRegionCode(this.props.region_code), this.districtSearch, this.map, this);
          // this.districtSearchByName('533103', this.districtSearch, this.map, this)
        }
      },
    };
  }

  // 清除地图覆盖物，重新绘制3D模型
  //其他组件监测到数据改变后，不重新画图，改为传递isSetColor给districtSearchByName来区分是改颜色还是重新绘制
  refreshMap() {
    if (!this.map) return
    this.districtSearchByName(formatterRegionCode(this.props.region_code), this.districtSearch, this.map, this , _ ,true);
  }
  componentDidMount() {
    this.props.onRef(this)
  }

  dispatchFetch = type => {
    const { dispatch, nameSpace } = this.props
    dispatch({
      type: selectModel(nameSpace, 'fetchMapQuery'),
      payload: type
    });
  };

  // 显示行政区名称marker
  showMarker(map, pointInfo) {
    const { name, center } = pointInfo;
    const { lat, lng } = center;
    if (this.marker) {
      this.marker.setMap(null)
    }
    this.marker = new AMap.Marker({
      content: name,
      position: [lng, lat],
      offset: new AMap.Pixel(-13, -10),
    });
    this.marker.setMap(map);
  }
  drawPolygon(data = {}, _map, _districtSearch, _this, regionColor = '#01c3df') {
    //根据boundaries绘制多边形
    const { boundaries, adcode, citycode, level, name, center } = data;
    const _extraData = {
      adcode,
      citycode,
      level,
      name,
      center,
      districtSearch: _districtSearch,
      _map: _map,
      _this: _this,
      boundaries: boundaries,
    }
    if (boundaries.length) {
      for (let i = 0, l = boundaries.length; i < l; i++) {
        let polygon = new AMap.Polygon({
          map: _map,
          strokeWeight: 1,
          strokeColor: '#ccc',
          fillColor: regionColor,
          zIndex: 999,
          // fillColor: '#343331',
          // fillOpacity: 0.8,
          path: boundaries[i],
          extData: _extraData,
        });
        let Marker = new AMap.Marker({
          map: _map,
          content: name,
          zIndex: 0,
          position: regionGeo[adcode] || [center.lng, center.lat],
        })
        polygon.on('click', this.handleClick);
        polygon.on('mouseover', (e) => this.handleCover(e));
        polygon.on('mouseout', (e) => this.handleOut(e));
      }
      //添加高度面
      const wall = new AMap.Object3D.Wall({
        path: boundaries,
        height: -80000,
        color: '#6d6d61'
      });
      wall.transparent = true
      _this.object3Dlayer.add(wall)
      _this.walls.push(wall)
      _map.setFitView(null, true, [-250, 0, 150, 0]); //地图自适应
    }
  }

  // 根据返回行政区与地图区域比较，不同值设置不同颜色
  matchDistinctColor(name, dataRow = [], fieldName = 'pre_square') {
    const colors = [ "#CC4A36", "#CE6E31", '#ffb300', '#f9cc37','#fbdc76', '#fff59d', '#efe9b1', '#9a996f']
    // const colors = ["#CC4A36", "#CE6E31", "#EBA743", '#fdd835', "#F1F076",  '#9a996f']
    let color = '#343331';
    const multiple = Math.floor(colors.length / dataRow.length)
    const mini = multiple == 0 ? 1 : multiple
    for (let y = 0; y < dataRow.length; y++) {
      const originRegion = name.slice(0, 2);
      const target = dataRow[y];
      const targetRegion = target.region_name.slice(0, 2);
      if (originRegion === targetRegion) {
        color = parseInt(target[fieldName]) ? colors[y * mini] : '#53514e';
        break;
      }
    }
    return color;
  }

  //根据下级地名进行循环绘制  _districtSearch：地级搜索插件实例   _list：下级地名列表
  mapDrawPolygon(_districtSearch, _list, _map, _this) {
    const { dataRow = [], fieldName } = _this.props;
    const dataSort = dataRow.sort((a, b) => parseFloat(b[fieldName]) - parseFloat(a[fieldName]));
    // const groupData = groupBy(dataSort, fieldName).reverse();
    const regionColors = {};
    _list.map((item, index) => {
      const { name } = item;
      const regionColor = this.matchDistinctColor(name, dataSort, fieldName);
      regionColors[name] = regionColor;
      _districtSearch.search(name, (status, result) => {
        if (status == 'complete') {
          const target = result.districtList.find(item => item.name === name)
          this.drawPolygon(target, _map, _districtSearch, _this, regionColor);
        }
      });
    });
    _this.setState({
      regionColors,
    });
    // _map.setFitView(null,null,[0,0,10,10]);//地图自适应
  }
  //改变线条颜色
  setPolygonColor(list){
    const { dataRow = [], fieldName } = this.props;
    const dataSort = dataRow.sort((a, b) => parseFloat(b[fieldName]) - parseFloat(a[fieldName]));
    const polygons = this.map.getAllOverlays('polygon')
    const regionColors = {};
    list.map((item,index) =>{
      const { name } = item
      const regionColor = this.matchDistinctColor(name, dataSort, fieldName);
      regionColors[name] = regionColor;
      for(let el of polygons){
        if(el.getExtData().name == name){
            el.setOptions({fillColor:regionColor})
        }
      }
    
    })
    this.setState({
      regionColors,
    });
  }

  //点击polygon事件
  handleClick(e) {
    const _data = e.target.Ce.extData;
    const { name, districtSearch, _map, level, _this, adcode } = _data;
    const { nameSpace, tabKey } = _this.props
    if (level === 'city') {
      _this.districtSearchByName(adcode, districtSearch, _map, _this);
    }
    if (level === 'district') {
      _this.setState({
        adcode,
        name,
        level,
      });
      _map.clearMap();
      const color = _this.state.regionColors[name];

      // _this.drawPolygon(_data, _map, districtSearch, _this, color);
      _this.districtSearchByName(adcode, districtSearch, _map, _this, color)
    }
    let value = {}
    value.data = _data
    value.type = mapQueyType(nameSpace, tabKey)
    _this.dispatchFetch(value)
    // _this.dispatchFetch(mapQueyType(nameSpace,tabKey))
  }

  //鼠标移入高亮
  handleCover(e) {
    const data = e.target.Ce.extData;
    e.target.setOptions({
      fillColor: '#01c3df',
    });
  }

  handleOut(e) {
    const _data = e.target.Ce.extData;
    const { name, _map } = _data;
    const color = this.state.regionColors[name] || '#343331';
    e.target.setOptions({
      fillColor: color,
    });
  }

  handleBack = async () => {
    const { adcode, level } = this.state
    const { dispatch, tabKey, nameSpace } = this.props
    this.map.clearMap()
    this.districtSearchByName(beforeAdcode(adcode, level), this.districtSearch, this.map, this)
    this.queryBefore(beforeAdcode(adcode, level), this.districtSearch)
  }

  //获得上一级相关数据
  queryBefore(_name, _districtSearch) {
    _districtSearch.search(_name, (status, result) => {
      if (status == 'complete') {
        const { dispatch, tabKey, nameSpace } = this.props
        let value = {}
        value.data = result.districtList[0]
        value.type = mapQueyType(nameSpace, tabKey)
        this.dispatchFetch(value)
        // this.dispatchFetch(mapQueyType(nameSpace,tabKey))
      }
    })
  }

  //主函数   已包含请求与dispatch
  //其他组件监测到数据改变后，不重新画图，改为传递isSetColor给districtSearchByName来区分是改颜色还是重新绘制
  districtSearchByName(_name, _districtSearch, _map, _this, color,isSetColor) {
    //根据name查询下级地级市并循环绘制
    _districtSearch.search(_name, (status, result) => {
      if (status == 'complete') {
        //result.districtList[0]包含了该级搜索的各类属性及数据{citycode,adcode,name,level,boundaries(自身的)}
        const { name, adcode, level } = result.districtList[0]
        const { dispatch, tabKey, nameSpace } = _this.props
        if (dispatch && this.state.queryAble) {
          // dispatch({
          //   type: selectModel(nameSpace, 'saveCurrentRegion'),
          //   payload: result.districtList[0]
          // })
          // this.dispatchFetch(mapQueyType(nameSpace,tabKey))
        }
        this.setState({
          //保存必要信息
          name,
          adcode,
          level,
          queryAble: true,
        });
        if (level !== 'district') {
          const subDistrictList = this.getSubDistrict(result.districtList[0], _map); //下级地名列表
          //subDistrictList是该搜索下级行政区域的name集合[{name,index},{}]
          if(isSetColor){
            this.setPolygonColor(subDistrictList)
          }else{
            this.mapDrawPolygon(_districtSearch, subDistrictList, _map, _this);
          }
        } else {
          this.walls.forEach(item => this.object3Dlayer.remove(item))
          this.drawPolygon(result.districtList[0], _map, _districtSearch, _this, color);
        }
      }
    });
  }

  getSubDistrict(_districtList, _map) {
    //获取下级行政区name列表
    const { districtList } = _districtList;
    let nameList = [];
    if (districtList) {
      districtList.map((item, index) => {
        const { name } = item;
        const listItem = { name, index };
        nameList.push(listItem);
      });
    }
    return nameList;
  }

  render() {
    const { currentUser, tabKey, unmountSign } = this.props;
    return (
      <div className={styles.mapWrapper}>
        {unmountSign == tabKey && (
          <Map
            events={this.amapEvents}
            mapStyle="dark"
            features={['bg']}
            viewMode="3D"
            rotation={45}
            pitch={45}
            pitchEnable={true}
          >
            <div className={styles.attentionArea}>
              <Row align="middle" gutter={[0, 8]}>
                <Col md={24} lg={24} xs={24}>
                  {this.state.adcode !== currentUser.region_code && (
                    <Button
                      onClick={this.handleBack.bind(this)}
                      className={styles.topButton}
                      icon={<RollbackOutlined />}
                    >
                      上一层
                    </Button>
                  )}
                </Col>
              </Row>
            </div>
          </Map>
        )}
      </div>
    );
  }
}
